package com.huitone.smspfm.socket.protocol.sgip.message;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.bin.common.utils.ArrayUtils;
import com.huitone.smspfm.socket.protocol.sgip.constant.CommandID;
import com.huitone.smspfm.socket.protocol.sgip.message.msgbody.IBody;
import com.huitone.smspfm.socket.protocol.sgip.message.msghead.Head;
import com.huitone.smspfm.socket.protocol.sgip.message.msghead.IHead;

/**   
* @Title Message.java 
* @Package com.huitone.smspfm.socket.protocol.sgip 
* @Description TODO(用一句话描述该文件做什么) 
* @author ybliang   
* @date 2017年3月24日 下午6:00:11 
* @version V1.0   
*/
public class Message implements IMessage {
	
	private static final Logger logger = LogManager.getLogger(Message.class);
	
	private IHead head;
	private IBody body;
	
	public Message(IHead head, IBody body) {
		
		if (head == null || body == null) {
			throw new RuntimeException("消息头和消息头都不能为空");
		}
		
		long commandIdB = CommandID.GetCommandIdByEntityClass.get(body.getClass());
		Head h = ((Head)head);
		long commandIdH = h.getCommandID();
		
		if (commandIdH != 0) {
			if (commandIdB != commandIdH) {
				h.setCommandID(commandIdB);
				logger.warn("Head的CommandID:" + commandIdH + "和body实体的CommandID:" + commandIdB + "不一致!");
			}
		} else {
			h.setCommandID(commandIdB);
		}
		
		this.head = head;
		this.body = body;
	}
	
	public static byte[] build(IHead head, IBody body) {
		
		if (head == null || body == null) {
			throw new RuntimeException("消息头和消息头都不能为空");
		}
		
		return new Message(head, body).toByteArray();
	}
	
	
	public byte[] toByteArray() {
		return ArrayUtils.addAll(head.toByteArray(), body.toByteArray());
	}

	
	public int length() {
		return head.length()+body.length();
	}

	public IHead getHead() {
		return head;
	}

	public void setHead(IHead head) {
		this.head = head;
	}

	public IBody getBody() {
		return body;
	}

	public void setBody(IBody body) {
		this.body = body;
	}

	
	public String toString() {
		return "Message [" + head + ", " + body + "]";
	}

	
	public String toSimpleString() {
		return head.toSimpleString() + " " + body.toSimpleString();
	}
}
